package com.teng.dataStructure.stack;

import java.util.Scanner;

/*
数组模拟栈
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5); // 数组模拟栈
        ArrayStack numsStack = new ArrayStack(20);
        ArrayStack operStack = new ArrayStack(20);
        String key = "";
        boolean loop = true;
        Scanner scanner = new Scanner(System.in); // 获取用户输入
        while (loop) {
            System.out.println("菜单");
            System.out.println("show：展示栈中的数据");
            System.out.println("push：给栈添加数据");
            System.out.println("pop：移除栈数据");
            System.out.println("exit：退出");
            key = scanner.next();
            switch (key) {
                case "show":
                    stack.show();
                    break;
                case "push":
                    System.out.println("请输入一个数：");
                    int value = scanner.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    int pop = stack.pop();
                    System.out.println("取出的数据为：" + pop);
                    break;
                case "exit":
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        scanner.close();
        System.out.println("程序已退出");
    }

}

class ArrayStack {
    private int maxSize; // 栈的最大容量
    private int[] stack; // 数组，用于模拟栈
    private int top = -1; // top表示栈顶，默认为-1

    public int getTop() {
        return top;
    }

    public void setTop(int top) {
        this.top = top;
    }

    // 构造器
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[maxSize];
    }

    // 栈满
    public boolean isFull() {
        return top - 1 == maxSize;
    }

    // 栈空
    public boolean isEmpty() {
        return top == -1;
    }

    // 出栈
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空！");
        }
        int value = stack[top];
        top--;
        return value;
    }

    public int showPop() {
        return stack[top];
    }

    // 入栈
    public void push(int value) {
        if (isFull()) {
            throw new RuntimeException("栈满！");
        }
        // 因为默认top=-1为空栈，所以先加再赋值；如果默认top=0，则先赋值再增
        top++;
        stack[top] = value;
    }

    // 遍历栈
    public void show() {
        if (isEmpty()) {
            throw new RuntimeException("栈空！");
        }
        for (int i = top; i >= 0; i--) {
            System.out.println(stack[i]);
        }
    }
}
